﻿// For an introduction to the Search Contract template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232512

// TODO: Add the following script tag to the start page's head to
// subscribe to search contract events.
//  
// <script src="/pages/search/search.js"></script>
//
// TODO: Edit the manifest to enable use as a search target.  The package 
// manifest could not be automatically updated.  Open the package manifest file
// and ensure that support for activation of searching is enabled.

(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var appModel = Windows.ApplicationModel;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var utils = WinJS.Utilities;
    var searchPageURI = "/pages/search/search.html";

    ui.Pages.define(searchPageURI, {
        _lastSearch: "",
        _page: 1,


        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            this._page = 1;
            this._registerEvent();
            this._lastSearch = options.queryText;
            document.querySelector(".titlearea .pagetitle").textContent = "搜索博主 “" + this._lastSearch + '”';
            this._searchData(this._lastSearch);
            $('#scroller').height($(document).height() - $(".search header").outerHeight());
            $('#to-top-floater').css({ 'margin-left': $(document).width() * 0.4 });

        },

        unload: function () {

        },

        // This function updates the page layout in response to viewState changes.
        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

        },
        
        _registerEvent: function () {
            var self = this;
            $('#scroller').scroll(function (e) {
                if (self.isloading)
                    return;

                var list = $('#scroller');
                var scrollTop = list.scrollTop(),
                    scrollHeight = list[0].scrollHeight,
                    listHeight = list.height();
                var differ = scrollTop + listHeight - scrollHeight;
                //if (differ > -100) {
                //    self._page++;
                //    self._searchData(self._lastSearch);
                //}

                //回到顶部是否可见
                if (scrollTop < 10) {
                    $('#to-top-floater').hide();
                }
                else {
                    $('#to-top-floater').show();
                }
            });

            $('#to-top-floater').click(function () {
                $('#scroller').animate({ scrollTop: 0 }, 300);
            });
        },

        // This function populates a WinJS.Binding.List with search results for the
        // provided query.
        _searchData: function (queryText) {
            var that = this;
            if (that.isloading) return;
            that.isloading = true;
            $('#progressBar').show();

            WinJS.xhr({ "url": "http://wcf.open.cnblogs.com/blog/bloggers/search?t=" + queryText }).done(
                function completed(result) {
                    that.isloading = false;
                    $('#progressBar').css("display", "none");
                    if (that._lastSearch != queryText) return;
                    if (result.status == 200) {
                        var data = $.xml2json(result.responseText);
                        if (that._page == 1)
                            $("#mainlist").empty();
                        $("#mainlist").append(template("SearchItemTemplate", data));

                        $(".timeline-item").removeAttr('onclick');
                        $(".timeline-item").click(function () {
                            var bloggerContent = $(this).attr('data-blogger');
                            var avatarContent = $(this).attr('data-avatar');
                            var authorContent = $(this).attr('data-author');
                            nav.navigate("/pages/main/main.html", { queryText: { blogger: bloggerContent, avatar: avatarContent, author: authorContent } });
                        });
                        //var first = $('#mainlist .item:first');
                        //first.addClass('timeline-item-current');
                        //if (first && first.length) {
                        //    self.showBlogContent(first[0]);
                        //}                        
                    }
                },
                function error(result) {
                    that.isloading = false;
                    $('#progressBar').css("display", "none");
                }
            );
        },

        isloading: false,
        //curPost: {
        //    id: "",
        //    title: {
        //        text: ""
        //    },
        //    updated: "",
        //    link: {
        //        href: ""
        //    },
        //    blogapp: "",
        //    avatar: "",
        //    postcount: 0,
        //},
    });

    WinJS.Application.addEventListener("activated", function (args) {
        if (args.detail.kind === appModel.Activation.ActivationKind.search) {
            args.setPromise(ui.processAll().then(function () {
                if (!nav.location) {
                    nav.history.current = { location: Application.navigator.home, initialState: {} };
                }

                return nav.navigate(searchPageURI, { queryText: args.detail.queryText });
            }));
        }
    });

    appModel.Search.SearchPane.getForCurrentView().onquerysubmitted = function (args) { nav.navigate(searchPageURI, args); };
})();
